package com.blockmeta.bbs.overallserviceapplication.search;

import android.content.Context;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Filterable;
import android.widget.TextView;

import com.blockmeta.bbs.baselibrary.base.adapter.BaseTabViewPagerAdapter;
import com.blockmeta.bbs.baselibrary.net.callback.MyStringCallback;
import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.StatusBarUtils;
import com.blockmeta.bbs.baselibrary.widget.tab.SlidingTabLayout;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.overallserviceapplication.R;
import com.blockmeta.bbs.overallserviceapplication.search.fragment.BBSListFragment;
import com.blockmeta.bbs.overallserviceapplication.search.fragment.CollegeListFragment;
import com.blockmeta.bbs.overallserviceapplication.search.fragment.ExchangeFragment;
import com.blockmeta.bbs.overallserviceapplication.search.fragment.FastSearchNewsFragment;
import com.blockmeta.bbs.overallserviceapplication.search.fragment.SearchCoinsResultFragment;
import com.blockmeta.bbs.overallserviceapplication.search.fragment.WeiboListFragment;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * Created by author on 2018/1/6.
 */

@SuppressWarnings("ALL")
public class SearchResultActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext;
    private View v;
    private AutoCompleteTextView tv;
    private TextView cancle;
    public String search;
    private SlidingTabLayout tab;
    private ViewPager vp;

    private List<String> tab_title;
    private List<Fragment> fragments;
    private boolean selectTag = true;
    private BaseTabViewPagerAdapter mBaseTabViewPagerAdapter;
    private String jumpTAG;

    private ArrayAdapter<String> mArrayAdapter;

    private boolean mBlockCompletion = true;

    public String mPreSearch;

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        mContext = SearchResultActivity.this;
        search = (String) getIntent().getExtras().get(Constant.SEARCH_COIN);
        mPreSearch = (String) getIntent().getExtras().get("word");
        jumpTAG = (String) getIntent().getExtras().get(Constant.ZERO);
        v = LayoutInflater.from(mContext).inflate(R.layout.activity_searchcoin_result, null);
        initData();
        return v;
    }

    @Override
    public void setStatusBarColor() {
        if (!"night".equals(SharedPreferenceUtil.getString(this, Constant.SKINTYPE, "light"))) {
            StatusBarUtils.setWindowStatusBarColor(this, R.color.status_color);
            StatusBarUtils.setDarkMode(this);
        } else {
            StatusBarUtils.setWindowStatusBarColor(this, R.color.status_red_night);
            StatusBarUtils.setDarkMode(this);
        }
    }

    private void initData() {
        tv = v.findViewById(R.id.coinsresult_tv);
        tv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mBlockCompletion||tv.isPerformingCompletion()) {return;}
                getAssociationalWord(s.toString());
                mPreSearch = s.toString();
            }
        });
        tv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                search = ((TextView)view.findViewById(R.id.tv_content)).getText().toString();
                initView();
            }
        });
        int height = StatusBarUtils.getStatusBarHeight();
        tv.setDropDownHeight(mContext.getResources().getDisplayMetrics().heightPixels-height- DimentionsUtil.dp2px(mContext,35));
        String[] a = new String[0];
        mArrayAdapter = new ArrayAdapter<String>(mContext,R.layout.item_drop_list,R.id.tv_content,a);
        tv.setAdapter(mArrayAdapter);
        cancle = (TextView) v.findViewById(R.id.coins_result_cancle);
        tab = v.findViewById(R.id.search_tablayout);
        vp = (ViewPager) v.findViewById(R.id.search_vp);
        cancle.setOnClickListener(this);
        setText(search);
        editSearchText();
        initView();
    }

    public void setText(String string){
        mBlockCompletion = true;
        tv.setText(string);
        tv.setSelection(string.length());
        mBlockCompletion = false;
    }

    /**
     * 获取联想词
     * @param s 引发联想
     */
    private void getAssociationalWord(final String s) {
        String url = NetConstant.GET_ASSOCIATIONAL_WORD+"?word="+s;
        OkHttpUtils.get()
                .addHeader("token", SharedPreferenceUtil.getString(mContext,Constant.TOKEN,null))
                .url(url)
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            String[] strings = new Gson().fromJson(response,String[].class);
                            if(strings != null && strings.length > 0) {
                                mArrayAdapter.clear();
                                mArrayAdapter.addAll(strings);
                            }
                            ((Filterable) mArrayAdapter).getFilter().filter(s,tv);
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    /**
     * 编辑搜索
     */
    private void editSearchText() {
        tv.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean isHide = actionId == EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES || actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode()
                        && KeyEvent.ACTION_DOWN == event.getAction()) || actionId == EditorInfo.IME_ACTION_GO;
                if (isHide) {
                    //隐藏软键盘
                    search = tv.getText().toString().trim();
                    if (search != null && !TextUtils.isEmpty(search)) {
                        tv.setText(search);
                        tv.setSelection(search.length());
                        initView();
                    }
                    hideKeyBoard();
                    return true;
                } else {
                    return false;
                }
            }
        });
    }

    private void hideKeyBoard() {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(
                    v.getApplicationWindowToken(), 0);
        }
    }


    private void initView() {
        tab_title = new ArrayList<>();
        fragments = new ArrayList<>();

        fragments = new ArrayList<>();
        fragments.add(SearchCoinsResultFragment.newInstance(search,mPreSearch));
        fragments.add(ExchangeFragment.instance(search));
        fragments.add((Fragment) RouterHelper.buildPath(RouterPath.INFOR_LIST_FRAGMENT).withString(Constant.ZERO,"keyword").withString(Constant.ONE,search).navigation());
        fragments.add(FastSearchNewsFragment.newInstance("keyword", search));
        fragments.add(WeiboListFragment.newInstance("keyword", search));
        fragments.add(RouterHelper.fragment(RouterPath.ACTIVE_LIST_FRAGMENT,"keyword",search));
        fragments.add(BBSListFragment.newInstance("keyword", search));
        fragments.add(CollegeListFragment.newInstance("keys", search));

        tab_title.add("项目");
        tab_title.add("交易所");
        tab_title.add("资讯");
        tab_title.add("快讯");
        tab_title.add("微博");
        tab_title.add("活动");
        tab_title.add("社区");
        tab_title.add("学院");

        initFragment();
    }

    private void initFragment() {
        //初始化ViewPager
        mBaseTabViewPagerAdapter = new BaseTabViewPagerAdapter(getSupportFragmentManager(), fragments, tab_title);
        vp.setAdapter(mBaseTabViewPagerAdapter);
        //预加载数量
        vp.setOffscreenPageLimit(fragments.size());
//        设置TabLayout和ViewPager绑定
        tab.setViewPager(vp);
        tab.setCurrentTab(getPositionByJumpTag(jumpTAG,tab_title),false);
    }

    /**
     * 根据收到的tag返回tabLayout应该显示的正确位置
     * @param tag 。
     * @param titles tabs
     * @return position
     */
    private int getPositionByJumpTag(String tag, List<String> titles) {
        int position = 0;
        for (String title : titles) {
            if (tag.contains(title)){
                return position;
            }
            ++position;
        }
        return 0;
    }
    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.coins_result_cancle) {
            finish();
        }
    }
}
